package user

import (
	"encoding/json"
	"errors"
	"fmt"
	"parking-lot-go-dingding/controller"
	"parking-lot-go-dingding/model/dingtalk/system"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func GetUserInfo(c *gin.Context) {

	requestStruct := struct {
		CorpId string `json:"corp_id"`
		Code   string `json:"code"`
	}{}

	//接收加密串
	if err := c.ShouldBindJSON(&requestStruct); err != nil {
		controller.Fail(c, "json接收失败")
		return
	}
	//获取access token
	accessToken, err := controller.AccessToken(requestStruct.CorpId)
	if err != nil {
		controller.Fail(c, "获取accesstoken失败"+err.Error())
		return
	}

	if accessToken == "" {
		controller.Fail(c, "获取accesstoken失败2")
		return
	}

	url := fmt.Sprintf("https://oapi.dingtalk.com/topapi/v2/user/getuserinfo?access_token=%s", accessToken)
	requestData := map[string]interface{}{
		"code": requestStruct.Code,
	}

	responseBody, err := controller.PostJsonRequest(url, requestData)
	//{"errcode":0,"errmsg":"ok","result":{"device_id":"a56699f9bf9dbd9a9321dff80566e1a8","name":"曹智博","sys":true,"sys_level":2,"unionid":"WX9UiiJsQvPFPJPAjZqhZiPgiEiE","userid":"204933504226167513"},"request_id":"15s1tfh7q809b"}

	responseStruct := struct {
		ErrCode int    `json:"errcode"`
		ErrMsg  string `json:"errmsg"`
		Result  struct {
			DeviceID string `json:"device_id"`
			Name     string `json:"name"`
			Sys      bool   `json:"sys"`
			SysLevel int    `json:"sys_level"`
			UnionID  string `json:"unionid"`
			UserID   string `json:"userid"`
		} `json:"result"`
		RequestID string `json:"request_id"`
	}{}

	err = json.Unmarshal(responseBody, &responseStruct)
	if err != nil {
		controller.Fail(c, "获取结果失败"+err.Error())
		return
	}

	//管理员身份判断
	var isAdmin bool
	var dingtalkSystemAdminStruct system.DingtalkSystemAdminStruct
	_, err = dingtalkSystemAdminStruct.First(requestStruct.CorpId, responseStruct.Result.UserID)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			isAdmin = false
		} else {
			controller.Fail(c, err.Error())
			return
		}
	} else {
		isAdmin = true
	}

	controller.Success(c, map[string]interface{}{
		"userid":   responseStruct.Result.UserID,
		"is_admin": isAdmin,
	})
}
